<template>
	<view class="video-com">
		<video
			class="video"
			:id="'_thisVideo_' + _uid"
			:poster="poster || ''"
			@play="onPlay"
			@pause="onPause"
			:src="src"
			:style="{height: height, width: width}"
		></video>
	</view>
</template>

<script>
	export default {
		props: {
			// 视频地址
			src: {
				type: String,
				default: 'https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/%E7%AC%AC1%E8%AE%B2%EF%BC%88uni-app%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D%EF%BC%89-%20DCloud%E5%AE%98%E6%96%B9%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B@20200317.mp4'
			},
			// 如非百分比 请带单位
			width: {
				type: String,
				default: "100%"
			},
			height: {
				type: String,
				default: "auto"
			},
			// 封面
			poster: {
				type: String,
				// 等待UI补充
				default: '/static/video_poster.png'
			},
			// 监听播放事件
			listenPlay: Function,
			// 监听暂停事件
			listenPause: Function
		},
		data() {
			return {
				videoContext: null,
				uid: 0
			}
		},
		methods:{
			// 视频播放时
			onPlay() {
				uni.$emit('listen-video-play', this.videoContext);
				this.$emit('listen-play', this.videoContext);
			},
			// 视频暂停时
			onPause() {
				this.$emit('listen-pause', this.videoContext);
			}
		},
		mounted() {
			this.videoContext = uni.createVideoContext('_thisVideo_' + this._uid, this);
			// 多处同时播放处理
			uni.$on('listen-video-play', (videoContext) => {
				if (videoContext !== this.videoContext) {
					// 同时只允许一个播放
					this.videoContext.pause();
				}
			})
			// 监听app hide 关闭后台运行
			uni.$on('app-hide', () => {
				try{
					console.log('~~~~~~~~app hide')
					this.videoContext.pause();
				}catch(e){
					//TODO handle the exception
				}
			})
			
		},
		// 销毁之前 停止视频播放
		beforeDestroy() {
			console.log('~!!!!!!!!!!!!!!!!!!!!!~~~~~~~~~~~~~~~~~~~~~~defore destroy')
			// uni.$off('listen-video-play');
			uni.$off('app-hide');
			// stop 无效
			this.videoContext.seek(0)
			this.videoContext.pause();
			this.videoContext = null;
		}
	}
</script>

<style lang="scss">
	.video-com{
		width: 100%;
	}
	.video {
		width: 100%;
	}
</style>
